package com.hxl.dailyworksummary.ai;

import com.hxl.dailyworksummary.settings.SettingsState;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

import java.util.List;
import java.util.Optional;

public class AIService {
    public Optional<String> summarizeWithAI(List<String> commits) {
        String token = SettingsState.getInstance().getState().aiToken;
        if (token.isEmpty()) {
            return formatSummary(commits).describeConstable();
        }

        if (commits.isEmpty()) {
            return "今天没有提交记录".describeConstable();
        }

        // 调用通义千问API
        return callQwenAPI(commits, token);
    }

    private Optional<String> callQwenAPI(List<String> commits, String token) {
        try {
            String commitText = String.join("\n", commits);
            String prompt = "请根据以下git提交信息，总结成一份工作日报，只需要列出完成了哪些功能点，不需要其他内容:\n" + commitText;

            // 创建OpenAI客户端，配置为使用通义千问API
            OpenAIClient client = OpenAIOkHttpClient.builder()
                    .apiKey(token)
                    .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                    .build();

            // 构建请求参数
            ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                    .addUserMessage(prompt)
                    .model("qwen3-max")
                    .build();

            // 发送请求并获取响应
            ChatCompletion chatCompletion = client.chat().completions().create(params);

            // 解析响应内容
            return parseAIResponse(chatCompletion);
        } catch (Exception e) {
            e.printStackTrace();
            return ("调用AI接口时发生错误: " + e.getMessage()).describeConstable();
        }
    }

    private Optional<String> parseAIResponse(ChatCompletion chatCompletion) {
        try {
            var choices = chatCompletion.choices();
            var choice = choices.get(0);
            var message = choice.message();
            return message.content();
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage().describeConstable();
        }
    }

    private String formatSummary(List<String> commits) {
        if (commits.isEmpty()) {
            return "今天没有提交记录";
        }

        StringBuilder sb = new StringBuilder();
        sb.append("今日工作内容总结：\n\n");

        for (int i = 0; i < commits.size(); i++) {
            sb.append((i + 1)).append(". ").append(commits.get(i)).append("\n");
        }

        sb.append("\n总结完毕。");
        return sb.toString();
    }
}